const WXAPI = require('apifm-wxapi')
const TOOLS = require('../../utils/tools.js')
const AUTH = require('../../utils/auth')
const CONFIG = require('../../config.js')
const APP = getApp()

Page({
  data: {
    qj: wx.getStorageSync("qj") ? wx.getStorageSync("qj") : 'bz',
    zdydh: wx.getStorageSync("zdydh") ? wx.getStorageSync("zdydh") : '',
    zdylogo: wx.getStorageSync("zdylogo") ? wx.getStorageSync("zdylogo") : '',
    dh_tap_index: 0,
    wishFoldersID: '',
    wishFolders: [],
    xyindex: 0,
    xyName: '',
    sywz: [],
  },
  onLoad: function (e) {
    this.setData({
      // wishFoldersID: e.id,
      // xyindex: e.index,
      wzid: e.wzid,
      xyName: e.xyName,
      inviter_id: e.inviter_id,
    });
    this.jzwz();
    // 设置title
    wx.setNavigationBarTitle({
      title: decodeURIComponent(this.data.xyName),
    })
    // this.loadWishFolders();
  },

  async jzwz() {
    const that = this;
    console.log("cc", that.data.wzid);

    try {
      // 解码并拆分ID
      const decodedStr = decodeURIComponent(that.data.wzid);
      const idList = decodedStr.split(",");

      // 过滤空ID（避免无效请求）
      const validIds = idList.filter(id => id.trim());
      if (validIds.length === 0) {
        that.setData({ sywz: [] });
        return;
      }

      // 并发请求所有接口，并等待全部完成
      const promises = validIds.map(id =>
        WXAPI.cmsArticleDetail(id).then(res => {
          // 只保留成功的数据
          return res.code === 0 ? res.data : null;
        })
      );

      // 等待所有请求完成
      const results = await Promise.all(promises);

      // 过滤掉失败的结果，按原ID顺序排列
      const allData = results.filter(data => data !== null);

      // 全部完成后设置数据
      that.setData({
        sywz: allData
      });
      console.log("所有接口调用完成", allData);

    } catch (error) {
      console.error("接口调用出错", error);
      // 出错时也设置空数据，避免页面异常
      that.setData({ sywz: [] });
    }
  },

  shareClick() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  showItems(e) {
    let index = e.currentTarget.dataset.index;
    let wzlx = e.currentTarget.dataset.wzlx;
    let wzid = e.currentTarget.dataset.wzid;
    console.log("dd", wzlx, wzid);

    if (wzlx == '200482') {
      wx.navigateTo({
        url: '/packageYt/case/detail_kt?id=' + wzid,
      })
    } else if (wzlx == '200483') {
      wx.navigateTo({
        url: '/packageYt/ting/detail_za?id=' + wzid,
      })
    } else {
      wx.navigateTo({
        url: '/packageYt/goods/detail?id=' + wzid,
      })
    }

  },


  // 加载心愿单文件夹
  loadWishFolders() {
    // 调用JSON接口获取文件夹列表
    WXAPI.jsonListV3({
      token: wx.getStorageSync('token'),
      type: "wish_folder",
      id: this.data.wishFoldersID,
      page: 1,
      pageSize: 100
    }).then(res => {
      if (res.code === 0) {
        this.setData({ wishFolders: res.data.result[0].content.data || [], wishFoldersID: res.data.result[0].id });
        console.log(this.data.wishFolders, this.data.wishFoldersID);
        let xyName = this.data.wishFolders[this.data.xyindex].name || '心愿单';
        // 设置标题
        wx.setNavigationBarTitle({
          title: xyName,
        })
        this.setData({ xyName: xyName });
        console.log("wishFolders", this.data.wishFolders);

      }
    });
  },
  zdy_top_nav() {
    wx.navigateTo({
      url: '/pages/xl/index',
    })
  },
  dh_tap(e) {
    //console.log(e);
    let temp = e.currentTarget.dataset.id;
    this.setData({
      dh_tap_index: temp
    })
    if (temp == 0) {
      wx.reLaunch({
        url: '/packageYt/index/index',
      })
    }
    if (temp == 1) {
      wx.reLaunch({
        url: '/packageYt/case/index',
      })
    }
    if (temp == 2) {
      wx.reLaunch({
        url: '/packageYt/ting/index',
      })
    }
    if (temp == 3) {
      wx.reLaunch({
        url: '/packageYt/goods/index',
      })
    }
    if (temp == 4) {
      wx.reLaunch({
        url: '/packageYt/my/index',
      })
    }
  },


  onShow: function (e) {
    this.setData({
      qj: wx.getStorageSync("qj") ? wx.getStorageSync("qj") : 'bz'
    })

  },

  async getGoodsList(categoryId, append) {
    if (categoryId == 0) {
      categoryId = "";
    }
    wx.showLoading({
      title: ''
    })
    // https://www.yuque.com/apifm/nu0f75/wg5t98
    const res = await WXAPI.goodsv2({
      categoryId: categoryId,
      page: this.data.curPage,
      pageSize: this.data.pageSize
    })
    wx.hideLoading()
    if (res.code == 404 || res.code == 700) {
      let newData = {
        loadingMoreHidden: false
      }
      if (!append) {
        newData.goods = []
      }
      this.setData(newData);
      return
    }
    let goods = [];
    if (append) {
      goods = this.data.goods
    }
    for (var i = 0; i < res.data.result.length; i++) {
      const item = res.data.result[i]
      const hidden_goods_index = wx.getStorageSync('hidden_goods_index')
      if (hidden_goods_index.indexOf(item.id) != -1) {
        continue
      }
      goods.push(item);
    }
    this.setData({
      loadingMoreHidden: true,
      goods: goods,
    });
  },

  onShareAppMessage: function () {
    return {
      title: this.data.qj == 'bz' || this.data.qj == 'hz' ? '心愿单丨' + decodeURIComponent(this.data.xyName) : decodeURIComponent(this.data.xyName),
      path: '/packageYt/my/xyd_share?wzid=' + this.data.wzid + '&xyName=' + decodeURIComponent(this.data.xyName) + '&inviter_id=' + wx.getStorageSync('uid'),
      // path: '/packageYt/my/xyd?id=' + this.data.wishFoldersID + '&index=' + this.data.xyindex + '&inviter_id=' + wx.getStorageSync('uid'),
      // title: '"' + wx.getStorageSync('mallName') + '" ' + wx.getStorageSync('share_profile'),
      // path: '/pages/index/index?inviter_id=' + wx.getStorageSync('uid')
    }
  },
  onShareTimeline() {
    return {
      title: this.data.qj == 'bz' || this.data.qj == 'hz' ? '心愿单丨' + decodeURIComponent(this.data.xyName) : decodeURIComponent(this.data.xyName),
      query: 'wzid=' + this.data.wzid + '&xyName=' + decodeURIComponent(this.data.xyName) + '&inviter_id=' + wx.getStorageSync('uid'),

      // path: '/packageYt/my/xyd?id=' + this.data.wishFoldersID + '&index=' + this.data.xyindex + '&inviter_id=' + wx.getStorageSync('uid'),
      // query: 'inviter_id=' + wx.getStorageSync('uid'),
      // imageUrl: wx.getStorageSync('share_pic')
    }
  },

  onReachBottom: function () {
    this.setData({
      curPage: this.data.curPage + 1
    });
    this.getGoodsList(0, true)
  },
  onPullDownRefresh: function () {
    this.setData({
      curPage: 1
    });
    this.getGoodsList(0)
    wx.stopPullDownRefresh()
  }
})